<template>
  <div>
    <table class="table table-hover">
      <thead>
        <tr>
          <th style="background:rgba(233, 163, 223, 0.2);">
            <!-- 表头中的复选框 -->
            <input type="checkbox" id="selectAll">
          </th>
          <!-- 循环出表头，用英文的逗号拆分字串 -->
          <th
            v-for="(item,index) in headerList.split(',')"
            :key="index"
            style="background:rgba(233, 163, 223, 0.2);"
          >{{item}}</th>
        </tr>
      </thead>
      <tbody>
        <!-- 循环出list中的每个对象 -->
        <tr v-for="(item,index) in bodyInfoList.slice(1, 999)" :key="index">
          <td>
            <!-- 表数据中首列复选框 -->
            <input
              name="userId"
              type="checkbox"
              :value="item[0]"
              class="selectSingle"
              @click="selectSingle()"
            >
          </td>
          <!-- 循环出对象的每个属性，展示时排除id -->
          <td
            v-for="(val,index) in item.slice(1, 99) "
            :key="index"
            style="color:#03d1f5d8;"
          >{{val}}</td>
        </tr>
      </tbody>
    </table>
    <paging></paging>
  </div>
</template>

<script>
import bus from "../../../../static/base/eventBus.js";
import paging from "./paging";

export default {
  name: "oneTable",
  components: {
    paging
  },
  props: {
    headerList: {
      type: String, // 亦可接收 Object 类型参数
      default: "headerList"
    },
    bodyInfoList: {
      type: Array,
      default: "bodyInfoList"
    }
  },
  methods: {
    // 全选一选
    selectSingle() {
      if ($(".selectSingle").length == $(".selectSingle:checked").length) {
        $("#selectAll").prop("checked", true);
      } else {
        $("#selectAll").prop("checked", false);
      }
      getCheckedUserIds(); // 删除
    }
  },
  mounted() {
    // 一选全选
    $("#selectAll").click(function(e) {
      $(".selectSingle").prop("checked", this.checked);
      getCheckedUserIds(); // 删除
    });
  },
  created() {
    // 监听刷新 -- 默认复选框未选中
    bus.$on("refresh", refresh => {
      if (refresh != null) {
        $('input[name="userId"]').prop("checked", false); //移除 checked 状态
        $("#selectAll").prop("checked", false);
      }
    });
  }
};

// 得选中值并传参到删除按钮
function getCheckedUserIds() {
  var boxs = $('input[name="userId"]');
  var userIds = [];
  for (var x in boxs) {
    if (boxs[x].checked) userIds.push(boxs[x].value);
  }
  // 兄弟组件传参：传参到修改、删除btn
  bus.$emit("userIds", userIds);
}
</script>

